<script setup lang="ts">
import { Globe24Regular as TranslateIcon } from '@vicons/fluent'
import { NIcon } from 'naive-ui/es/icon'
import { storeToRefs } from 'pinia'
// 移除其他语言图标导入
import ChineseIcon from '../CustomIcons/ChineseIcon.vue'
import EnglandIcon from '../CustomIcons/EnglandIcon.vue'

defineProps<{ showTitle?: boolean }>()
const { t } = useI18n()
const layoutStore = useLayoutStore()
const { activeLanguage } = storeToRefs(layoutStore)
const { availableLocales } = useI18n()
const language = ref(activeLanguage)

// 修改这里：只保留中文和英文
const languages = availableLocales
  .filter(x => ['en', 'cn'].includes(x)) // 过滤语言
  .sort(sortLangs)
  .map((x) => {
    return {
      label: () => renderLabel(t(`languages.${x}`), x),
      value: x,
    }
  })

function changeLanguage(lang: string) {
  layoutStore.changeLanguage(lang)
  layoutStore.resetWelcomeState()
  // setTimeout(() => window.location.reload(), 1500)
}

function renderLabel(label: string, language: string) {
  return h('div', { class: 'flex items-center gap-2' }, [
    h(getLanguageIcon(language)),
    h('span', null, { default: () => label }),
  ])
}

// 修改这里：只保留中文和英文图标
function getLanguageIcon(language: string) {
  switch (language) {
    case 'en':
      return EnglandIcon
    case 'cn':
      return ChineseIcon
    default:
      return EnglandIcon
  }
}

// 修改这里：更新排序函数以适应只有两种语言的情况
function sortLangs(a: string, b: string): number {
  const ordered = ['en', 'cn']
  return ordered.findIndex((x) => x === a) - ordered.findIndex((x) => x === b)
}
</script>

<template>
  <div v-bind="$attrs">
    <n-popselect v-model:value="language" trigger="hover" :options="languages" @update-value="changeLanguage">
      <n-button quaternary :circle="!showTitle">
        <template #icon>
          <NIcon size="1.4rem">
            <TranslateIcon />
          </NIcon>
        </template>
        <span v-if="showTitle">{{ t(`languages.${activeLanguage}`) }}</span>
      </n-button>
    </n-popselect>
  </div>
</template>

<style lang="scss" scoped></style>